<template>
  <div class="module-layout">
    <je-panel v-bind="options">
      <template #top>
        <div
          class="source-module-box"
          :style="{
            borderBottom: borderBottomPanes.includes(curModuleCode) ? '1px solid #e6e6e6' : '',
          }"
        >
          <div
            v-for="moduleItem in moduleOptions"
            :key="moduleItem.code"
            class="module-item"
            :class="{ 'active-module-item': moduleItem.code == curModuleCode }"
            @click="changeModuleCode(moduleItem.code)"
            >{{ moduleItem.name }}</div
          >
        </div>
      </template>
      <template #default>
        <div v-show="curModuleCode == viewOptionType.DESIGN_VIEW">
          <!-- :line-data="lineData"
            :table-data="tableData" -->
          <source-view-design
            ref="designRef"
            :design-datas="designDatas"
            :concern-datas="concernDatas"
            @chageCheckData="chageCheckData"
            @changeTableData="changeTableData"
            @deleteConcernTableData="deleteConcernTableData"
          />
        </div>
        <div v-show="curModuleCode == viewOptionType.CONNECT_VIEW">
          <design-connect
            ref="connectRef"
            :concern-datas="concernDatas"
            :delete-table-id="deleteTableId"
            @getConcernTable="getConcernTable"
            @changeLine="changeLine"
          />
        </div>
        <div v-show="curModuleCode == viewOptionType.QUERY_VIEW">
          <design-query ref="queryRef" :base-table="concernDatas.selectDatas" />
        </div>
        <div v-show="curModuleCode == viewOptionType.OUTPUT_VIEW">
          <source-view-output :out-put-data="outPutData" @setChangeType="setChangeType" />
        </div>
        <div v-if="curModuleCode == viewOptionType.DDL_VIEW">
          <source-view-ddl />
        </div>
      </template>
    </je-panel>
  </div>
</template>

<script>
  import { defineComponent, reactive, ref, toRefs, onMounted, watch, nextTick } from 'vue';
  import SourceViewDesign from '@/views/data-source/source-view/components/source-view-design.vue';
  import DesignConnect from '@/views/data-source/source-view/components/design-connect.vue';
  import DesignQuery from '@/views/data-source/source-view/components/design-query.vue';
  import SourceViewOutput from '@/views/data-source/source-view/components/source-view-output.vue';
  import SourceViewDdl from '@/views/data-source/source-view/components/source-view-ddl.vue';
  import { useSourceStore } from '@/store/source-store';
  import VueEvent from '@/helper/event';
  import { SOURCE_VIEW_OPTIONS, VIEW_OPTION_TYPE, SOURCE_START_RECOVER } from '@/helper/constant';
  export default defineComponent({
    name: 'SourceModule',
    components: {
      SourceViewDesign,
      DesignConnect,
      DesignQuery,
      SourceViewOutput,
      SourceViewDdl,
    },
    props: {
      //视图设计引入的资源表
      tableData: {
        type: Array,
        default: () => [],
      },
      //开始load关联设计
      reloadRelevan: {
        type: Boolean,
        default: () => {
          return false;
        },
      },
    },
    setup(props) {
      const sourceStore = useSourceStore(); //数据源全局状态
      const curSourceCode = sourceStore.getSourceCode(); //当前资源表code
      const designRef = ref(null); //设计视图
      const connectRef = ref(null); //关联设计
      const state = reactive({
        options: {
          left: {
            size: 200,
            maxSize: 200,
            minSize: 200,
            split: true,
            collapsible: true,
            collapsed: true,
            style: { borderRight: '1px solid #ecedf0' },
          },
          top: { size: 40, split: false },
          bottom: { size: 300, split: false },
        },
        curTabSourceCode: sourceStore.getSourceCode(),
        moduleOptions: SOURCE_VIEW_OPTIONS,
        curModuleCode: SOURCE_VIEW_OPTIONS[0].code, //当前模块code
        viewOptionType: VIEW_OPTION_TYPE, //视图下模块分类
        //输出视图数据
        outPutData: [],
        tableDataTypes: { concern: false, output: false },
        //关联设计对应选择数据
        concernDatas: {
          selectDatas: [], //下拉框数据
          tabelData: [],
        },
        deleteTableId: '', //删除对应关系表id
        designDatas: { tableDatas: [], tableCodes: [], lineinfo: [] },
        borderBottomPanes: ['DESIGN_VIEW', 'QUERY_VIEW', 'DDL_VIEW'], //底部有线的pane
      });
      const methods = {
        changeModuleCode(code) {
          //切换
          if (state.curModuleCode != code) {
            state.curModuleCode = code;
          }
        },
        setChangeType() {
          state.tableDataTypes.output = true;
        },
        chageCheckData(data, records) {
          //监听设计视图table选中事件
          methods.setChangeType();
          if (data.type == 'add') {
            delete data.type;
            state.outPutData.push(data);
          } else if (data.type == 'addAll') {
            //先删除
            for (let index = 0; index < state.outPutData.length; index++) {
              const item = state.outPutData[index];
              if (item.tableCode == data.tableCode) {
                state.outPutData.splice(index, 1);
                index--;
              }
            }
            //在添加
            records.forEach((rec) => {
              var obj = {
                value: data.tableCode + '.' + rec.TABLECOLUMN_CODE,
                tableCode: data.tableCode,
                column: rec.TABLECOLUMN_CODE,
                name: rec.TABLECOLUMN_NAME,
                dataType: rec.TABLECOLUMN_TYPE,
                length: rec.TABLECOLUMN_LENGTH,
                grouping: false,
                sort: '',
                formula: '',
                whereColum: '',
              };
              state.outPutData.push(obj);
            });
          } else if (data.type == 'delete') {
            state.outPutData.forEach((item, index) => {
              if (item.value == data.value) {
                state.outPutData.splice(index, 1);
              }
            });
          } else if (data.type == 'deleteTable') {
            for (let index = 0; index < state.outPutData.length; index++) {
              const item = state.outPutData[index];
              if (item.tableCode == data.tableCode) {
                state.outPutData.splice(index, 1);
                index--;
              }
            }
          }
          const curSourceCode = sourceStore.getSourceCode();
          const curSourceData = sourceStore.getSourceDataByCode(curSourceCode);
          curSourceData.DATASOURCE_OUTPUT_COLUMNS = JSON.stringify(state.outPutData);
        },
        //视图资源表发生变化
        changeTableData(concernDatas) {
          state.concernDatas = concernDatas;
        },
        //设置关联视图
        setDeisgnData(designData) {
          const curSourceCode = sourceStore.getSourceCode();
          const curSourceData = sourceStore.getSourceDataByCode(curSourceCode);
          curSourceData.DATASOURCE_BASE_TABLE = JSON.stringify(designData);
        },
        //关联设计table对象
        getConcernTable(obj) {
          state.concernDatas.tableObj = obj;
        },
        //关联设计的数据发生变化
        changeLine(row) {
          // state.lineData = row;
          designRef.value.changeLine(row);
        },
        //删除关系设置的数据表 tableId
        deleteConcernTableData(tableId) {
          state.deleteTableId = tableId;
        },
        //初始化输出视图
        initOutputView() {
          const curSourceCode = sourceStore.getSourceCode();
          const curSourceData = sourceStore.getSourceDataByCode(curSourceCode);
          if (curSourceData.DATASOURCE_OUTPUT_COLUMNS) {
            const outputData = JSON.parse(curSourceData.DATASOURCE_OUTPUT_COLUMNS);
            state.outPutData = outputData;
            const designChecked = {};
            outputData.forEach((item) => {
              const key = item.tableCode;
              if (typeof designChecked[key] != 'object') {
                designChecked[key] = [];
              }
              designChecked[key].push(item.value.split('.')[1]);
            });
            methods.loadConcernData(designChecked);
          }
        },
        loadConcernData(designChecked) {
          const viewinfo = [];
          const lineinfo = [];
          const curSourceCode = sourceStore.getSourceCode();
          const curSourceData = sourceStore.getSourceDataByCode(curSourceCode);
          if (curSourceData.DATASOURCE_INCIDENCE_RELATION) {
            const tabelData = JSON.parse(curSourceData.DATASOURCE_INCIDENCE_RELATION);
            for (const concernItem of tabelData) {
              //连线数据组装
              if (concernItem.isDispalyLine) {
                lineinfo.push({
                  mainTableId: concernItem.mainTableId,
                  mainIdentifier: concernItem.mainIdentifier,
                  targetTableId: concernItem.targetTableId,
                  targetIdentifier: concernItem.targetIdentifier,
                  isDispalyLine: concernItem.isDispalyLine,
                });
              }
            }
            state.concernDatas.tabelData = tabelData;
            connectRef.value.loadConcernData(state.concernDatas.tabelData);
          } else {
            state.concernDatas.tabelData = [];
            connectRef.value.loadConcernData([]);
          }
          if (curSourceData.DATASOURCE_BASE_TABLE) {
            const tableList = JSON.parse(curSourceData.DATASOURCE_BASE_TABLE);
            state.concernDatas.selectDatas = [];
            tableList.forEach((item) => {
              state.concernDatas.selectDatas.push({
                tableCode: item.tableCode,
                tableId: item.tableId,
                tableName: item.tableName,
                value: item.tableCode,
                label: item.tableName,
              });
              item.queryType = 'PRO,SYS';
              item.sourceCode = curSourceCode;
              item.selectCode = designChecked[item.tableCode];
              viewinfo.push(item);
            });
          }
          state.designDatas.tableDatas = viewinfo;
          state.designDatas.lineinfo = lineinfo;
        },
        //复原输出视图
        resoverOutputView() {
          const curSourceCode = sourceStore.getSourceCode();
          const curSourceData = sourceStore.getSourceDataByCode(curSourceCode);
          if (curSourceData.DATASOURCE_OUTPUT_COLUMNS) {
            const outputData = JSON.parse(curSourceData.DATASOURCE_OUTPUT_COLUMNS);
            state.outPutData = outputData;
            const designChecked = {};
            outputData.forEach((item) => {
              const key = item.tableCode;
              if (typeof designChecked[key] != 'object') {
                designChecked[key] = [];
              }
              designChecked[key].push(item.value.split('.')[1]);
            });
            methods.recoverConcernData(designChecked);
          } else {
            //选择的表信息
            state.designDatas.tableDatas = curSourceData.DATASOURCE_BASE_TABLE
              ? JSON.parse(curSourceData.DATASOURCE_BASE_TABLE)
              : [];
            state.concernDatas.selectDatas = curSourceData.DATASOURCE_BASE_TABLE
              ? JSON.parse(curSourceData.DATASOURCE_BASE_TABLE)
              : [];
            //关联设计
            const lineinfo = [];
            if (curSourceData.DATASOURCE_INCIDENCE_RELATION) {
              const tabelData = JSON.parse(curSourceData.DATASOURCE_INCIDENCE_RELATION);
              for (const concernItem of tabelData) {
                //连线数据组装
                if (concernItem.isDispalyLine) {
                  lineinfo.push({
                    mainTableId: concernItem.mainTableId,
                    mainIdentifier: concernItem.mainIdentifier,
                    targetTableId: concernItem.targetTableId,
                    targetIdentifier: concernItem.targetIdentifier,
                    isDispalyLine: concernItem.isDispalyLine,
                  });
                }
              }
              state.concernDatas.tabelData = tabelData || [];
            } else {
              state.concernDatas.tabelData = [];
            }
            connectRef.value.loadConcernData(state.concernDatas.tabelData);
            state.designDatas.lineinfo = lineinfo;
          }
        },
        recoverConcernData(designChecked) {
          const viewinfo = [];
          const lineinfo = [];
          const curSourceCode = sourceStore.getSourceCode();
          const curSourceData = sourceStore.getSourceDataByCode(curSourceCode);
          if (curSourceData.DATASOURCE_INCIDENCE_RELATION) {
            const tabelData = JSON.parse(curSourceData.DATASOURCE_INCIDENCE_RELATION);
            for (const concernItem of tabelData) {
              //连线数据组装
              if (concernItem.isDispalyLine) {
                lineinfo.push({
                  mainTableId: concernItem.mainTableId,
                  mainIdentifier: concernItem.mainIdentifier,
                  targetTableId: concernItem.targetTableId,
                  targetIdentifier: concernItem.targetIdentifier,
                  isDispalyLine: concernItem.isDispalyLine,
                });
              }
            }
            state.concernDatas.tabelData = tabelData;
          }
          if (curSourceData.DATASOURCE_BASE_TABLE) {
            const tableList = JSON.parse(curSourceData.DATASOURCE_BASE_TABLE);
            state.concernDatas.selectDatas = [];
            tableList.forEach((item) => {
              state.concernDatas.selectDatas.push({
                tableCode: item.tableCode,
                tableId: item.tableId,
                tableName: item.tableName,
                value: item.tableCode,
                label: item.tableName,
              });
              item.queryType = 'PRO,SYS';
              item.sourceCode = curSourceCode;
              item.selectCode = designChecked[item.tableCode];
              viewinfo.push(item);
            });
          }
          state.designDatas.tableDatas = viewinfo;
          state.designDatas.lineinfo = lineinfo;
        },
        //复原数据源数据
        recoverSourceData(sourceCode) {
          if (state.curTabSourceCode == sourceCode) {
            methods.resoverOutputView();
          }
        },
      };
      watch(
        () => props.tableData,
        (val) => {
          val.forEach((tableItem) => {
            designRef.value.addViewTable(tableItem);
          });
        },
        { deep: true },
      );
      watch(
        () => props.reloadRelevan,
        (val) => {
          if (val) {
            connectRef.value.reloadRelevanData();
          }
        },
      );
      onMounted(() => {
        nextTick(() => {
          methods.initOutputView();
        });
        VueEvent.on(SOURCE_START_RECOVER, methods.recoverSourceData);
      });
      return {
        designRef,
        connectRef,
        ...toRefs(state),
        ...methods,
      };
    },
  });
</script>
<style scoped lang="less">
  .module-layout {
    width: 100%;
    height: 100%;
  }
  .source-module-box {
    width: 100% !important;
    height: 40px !important;
    display: flex;
    box-sizing: border-box;
    background-color: #fafafa;
    // border-bottom: 1px solid #ecedf0;
    .module-item {
      width: 106px;
      height: 40px;
      text-align: center;
      line-height: 40px;
      border-right: 1px solid #ecedf0;
      cursor: pointer;
    }
  }
</style>
